package com.navidove.commons.type;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;

import com.navidove.commons.vo.EnhanceEnum;

public class EnumType extends org.hibernate.type.EnumType {

    private static final long serialVersionUID = -8560896083230599029L;

    public void setParameterValues(Properties parameters) {
        parameters.setProperty(TYPE,  String.valueOf(Types.VARCHAR));
        super.setParameterValues(parameters);
    }

    /**
     * @see org.hibernate.type.EnumType#nullSafeGet(java.sql.ResultSet, java.lang.String[], org.hibernate.engine.spi.SessionImplementor, java.lang.Object)
     */
    public Object nullSafeGet(ResultSet rs, String[] names,
    		SessionImplementor session, Object owner) throws SQLException {
        Object object = rs.getObject( names[0] );
        if (object == null) return null;
                
        Object rtnVal = null;
        if (EnhanceEnum.class.isAssignableFrom(returnedClass())) {
            Object[] values = returnedClass().getEnumConstants();
            for (Object value : values) {
                if (object.toString().equals(((EnhanceEnum) value).getCode())) {
                    rtnVal = value;
                    break;
                }
            }
        }
        if (rtnVal != null) {
            return rtnVal;
        }
        try {
            rtnVal = super.nullSafeGet(rs, names, session, owner);
        } catch (IllegalArgumentException e) {
        }
        return rtnVal;       
    }
    
    /**
     * @see org.hibernate.type.EnumType#nullSafeSet(java.sql.PreparedStatement, java.lang.Object, int, org.hibernate.engine.spi.SessionImplementor)
     */
    public void nullSafeSet(PreparedStatement st, Object value, int index,
    		SessionImplementor session) throws HibernateException, SQLException {
        if (value instanceof EnhanceEnum) {
            st.setObject( index, ((EnhanceEnum) value).getCode(), Types.VARCHAR );
        } else if (value instanceof String) {
        	st.setObject( index, value, Types.VARCHAR );
        } else {
            super.nullSafeSet(st, value, index, session);
        }
    }
}
